import {Action} from "routing-controllers";
import { Service } from "typedi";

@Service()
export class ResultDataMiddlewares {
	private _status : number;
	private _data: Object;
	private _methods;
	private _url;

	get status(): number {
		return this._status;
	}

	set status(value: number) {
		this._status = value;
	}

	get data(): Object {
		return this._data;
	}

	set data(value: Object) {
		this._data = value;
	}
	get methods() {
		return this._methods;
	}

	set methods(value) {
		this._methods = value;
	}

	get url() {
		return this._url;
	}

	set url(value) {
		this._url = value;
	}

	/**
	 * 数据请求成功
	 * @param _data 需要返回给前端的数据
	 */
	public success (_data:Object): string {
		this.status = 200;
		this.data = _data;
		return JSON.stringify({
			status: this.status,
			result: this.data
		})
	}

	/**
	 * 数据请求失败
	 * @param action 请求对象
	 */
	public error (action: Action,message: string): string {
		this.status = action.response.status; // 状态码
		this.data = message;  // 错误信息
		this.methods = action.request.method; // 请求方式
		this.url = action.request.url;        // 请求地址
		return JSON.stringify({
			methods: this.methods,
			status: this.status,
			result: this.data,
			url: this.url
		})
	}
}